<?php
namespace app\api\controller;
use think\Controller;
use think\Config;
use think\Cache;
use think\Db;
use think\Validate;
use think\log;
class Personal extends Controller{
    //商户ID
    public $merchantCode = '61957441';
    //DES的密钥
    public $des_key = 's8h7u6i5';
    //白条公钥
    public $public_pfile = "./extend/Jdbaitiao/baitiao_public.key";
    //商户公钥
    public $public_file  = "./extend/Jdbaitiao/public.key";
    //商户私钥
    public $private_file = "./extend/Jdbaitiao/private.key";

    //获取手机号验证码
    public function getVerificationCode(){
        $account = Config::get('chuanglan.account');
        $password = Config::get('chuanglan.password');
        $phone = input('post.phone');
        // $phone = '13544582564';
        if($phone == '' || $phone == 'undefined' || $phone == 'null'){
            $info['code'] = 401;
            $info['msg'] = '参数缺失';
            return json($info);
        }
        $preg_phone='/^1[34578]\d{9}$/ims';
        if(!preg_match($preg_phone,$phone)){
            $info['code'] = 401;
            $info['msg'] = '手机格式不正确';
            return json($info);
        }
        $msgSign = Config::get('chuanglan.msgSign');
        $code = mt_rand(1000,9999);
        $cache_name = 'phone'.$phone;
        Cache::set($cache_name,$code,180);
        $msg = $msgSign.'您好,您的验证码是'.$code;
        $data['account'] = $account;
        $data['pswd'] = $password;
        $data['msg'] = urlencode($msg);
        $data['mobile'] = $phone;
        $data['needstatus'] = 'false';
        $data['product'] = '';
        $data['extno'] = '';
        Log::write('发送短信验证码前夕，发送内容'.$msg.'，手机号'.$phone,'info');
        $result = $this->curl_post($data);
        if($result){Log::write('发送短信验证码发送成功，手机号'.$phone.'，返回值'.$result,'info');
            return json_encode(array('code'=>200,'msg'=>'验证码发送成功'));
        }else{Log::write('发送短信验证码发送失败，手机号'.$phone.'，返回值'.$result,'debug ');
            return json_encode(array('code'=>201,'msg'=>'验证码发送失败'));
        }
        
    }

    public function curl_post($array){
        $curl = curl_init();
        $header = array(
            "Content-Type:application/x-www-form-urlencoded",
            "Accept:text/plain"
        );
        //设置提交的url
        $url = "http://222.73.117.158/msg/HttpBatchSendSM";
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        $post_data = http_build_query($array);

        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

        //执行命令
        $data = curl_exec($curl);

        //关闭URL请求
        curl_close($curl);
        //获得数据并返回
        return $data;
    }

    //绑定手机号
    public function binding(){
        $user_id = input('post.user_id');
        $phone = input('post.phone');

        $verification_code = input('verification_code');
        if($phone == 'undefined' || $phone == 'null' || $phone == ''){
            return json_encode(array('code'=>401,'msg'=>'缺少手机号'));
        }elseif($verification_code =='undefined' || $verification_code == 'null' || $verification_code == ''){
            return json_encode(array('code'=>401,'msg'=>'缺少验证码'));
        }elseif(!is_numeric($user_id)){
            return json_encode(array('code'=>401,'msg'=>'用户id类型异常'));
        }
        $cache_name = 'phone'.$phone;
        $code = Cache::get($cache_name);
        if(!$code){
            return json_encode(array('code'=>401,'msg'=>'验证码过期'));
        }
        if($code != $verification_code){
            return json_encode(array('code'=>401,'msg'=>'验证码错误'));
        }
        $data['phone'] = $phone;
        $binding_phone = db('user')->where("user_id = {$user_id}")->update($data);
        if($binding_phone){
            return json_encode(array('code'=>200,'msg'=>'手机号绑定成功'));
        }else{
            return json_encode(array('code'=>201,'msg'=>'手机号绑定失败'));
        }
    }

    //解绑手机号
    public function untiedPhone(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $map = "user_id = {$user_id}";
        $user_phone = db('user')->where($map)->value('phone');
        $phone = input('post.phone');
        if($phone != $user_phone){
            return json_encode(['code'=>401,'msg'=>'phone参数不正确']);
        }
        $untied_phone = db('user')->where($map)->update(['phone'=>'']);
        if($untied_phone){
            return json_encode(['code'=>200,'msg'=>'解绑成功']);
        }else{
            return json_encode(['code'=>201,'msg'=>'解绑失败']);
        }

    }

    //返回手机号
    public function getPhone(){
        $user_id = input('post.user_id');
        $user_info = db('user')->field('time,phone,jd_integral')->where("user_id = {$user_id}")->find();
        $user_info['time'] = date("Y年m月d日 H:i",$user_info['time']);
        return json_encode([
                          'code'=>200,
                          'msg'=>'请求成功',
                          'add_time'=>$user_info['time'],
                          'phone'=>$user_info['phone'],
                          'jd_integral'=>$user_info['jd_integral']
                          ]);
    }

    //我的信息
    public function myInfo(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $user_info = db('user')->field('jd_openid,jd_integral,quota,frozen_integral,available_integral')
                               ->where("user_id = {$user_id}")
                               ->find();
//        if($user_info['jd_integral'] == "0.00"){
//            $user_info['frozen_integral'] = 0.00;
//            $user_info['available_integral'] = 0.00;
//        }
        $jd_info = array('jd_openid'=>$user_info['jd_openid']);
        return json_encode(['code'=>200,'msg'=>'请求成功','jd_integral'=>$user_info['jd_integral'],'quota'=>$user_info['quota'],'frozen_integral'=>$user_info['frozen_integral'],'available_integral'=>$user_info['available_integral'],'jd_info'=>$jd_info]);
        
    }

    //绑定京东小白
    public function bindingJdCredit(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $jd_name = input('post.jd_name');
        if($jd_name == '' || $jd_name == 'null' || $jd_name == 'undefined'){
            return json_encode(['code'=>401,'msg'=>'账户姓名不能为空']);
        }
        $jd_phone = input('post.jd_phone');
        if($jd_phone == '' || $jd_phone == 'null' || $jd_phone == 'undefined'){
            return json_encode(['code'=>401,'msg'=>'手机号码不能为空']);
        }
        $preg_phone='/^1[34578]\d{9}$/ims';
        if(!preg_match($preg_phone,$jd_phone)){
            return json_encode(['code'=>401,'msg'=>'手机号码格式不正确']);
        }
        $id_number = input('post.id_number');
        if($id_number == '' || $id_number == 'null' || $id_number == 'undefined'){
            return json_encode(['code'=>401,'msg'=>'身份证号码不能为空']);
        }
        if(!validateIDCard($id_number)){
            return json_encode(['code'=>401,'msg'=>'身份证号码不正确']);
        }
        $data = array('jd_name'=>$jd_name,'jd_phone'=>$jd_phone,'id_number'=>$id_number);
        $binding_jd_credit = db('user')->where("user_id = {$user_id}")->update($data);
        if($binding_jd_credit){
            return json_encode(['code'=>200,'msg'=>'京东小白信用绑定成功']);
        }else{
            return json_encode(['code'=>201,'msg'=>'京东小白信用绑定失败']);
        }
    }

    //京东小白信用解绑
    public function untiedJdCredit(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $map = "user_id = {$user_id}";
        $frozen_integral = db('user')->where($map)->value('frozen_integral');
        if($frozen_integral > 0){return json_encode(['code'=>401,'msg'=>'该京东小白信用正在使用中,请勿解绑']);}
        $data = array('jd_name'=>'','jd_phone'=>'','id_number'=>'','jd_integral'=>'','quota'=>'','frozen_integral'=>'','available_integral'=>'','jd_integral_time'=>'');
        $untied_jd_credit = db('user')->where($map)->update($data);
        if($untied_jd_credit){
            return json_encode(['code'=>200,'msg'=>'京东小白信用解绑成功']);
        }else{
            return json_encode(['code'=>201,'msg'=>'京东小白信用解绑失败']);
        }
    }

    //关于享珠珠
    public function aboutUs(){
        if(cache('company_information')){
            $company_information = cache('company_information');
        }else{
        $list = Db::name("config")->where("type='js'")->select();
        foreach ($list as $rs){
            $config[$rs['name']] = $rs['value'];
        }
        $company_information = array(
           'img' => 'https://'.$_SERVER['HTTP_HOST'].$config['img'],
           'introduction' => $config['introduction'],
           'name' => $config['name'],
           'telephone' => $config['telephone'],
           'address' => $config['address'],
            );
            cache('company_information',$company_information,30);
        }
        if($company_information){
            return json_encode(['code'=>200,'msg'=>'请求成功','company_information'=>$company_information]);
        }
    }

    //我的收藏列表
    public function myCollectionList(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $page = input('post.page');
        if($page){
            if(!is_numeric($page)){
                return json_encode(array('code'=>401,'msg'=>'page参数类型有误'));
             }
        }else{
            $page = 0;
        }
        $collection_list = db('goods_collection')->field('goods_id')
                                                 ->where("user_id = {$user_id}")
                                                 ->order('create_time desc')
                                                 ->limit($page*6,6)
                                                 ->select();
        foreach($collection_list as $key=>$value){
            $map = "goods_id = {$collection_list[$key]['goods_id']}";
            $goods_info = db('goods')->field('name,mode,thumbnail_img,small,sale_type')->where($map)->find();
            $collection_list[$key]['name'] = $goods_info['name'];
            $collection_list[$key]['mode'] = $goods_info['mode'];
            if(!Validate::is($goods_info['thumbnail_img'],'url')){
                $collection_list[$key]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$goods_info['thumbnail_img'];
            }
            $collection_list[$key]['small'] = $goods_info['small'];
            $collection_list[$key]['sale_type'] = $goods_info['sale_type'];
        }
        if($collection_list){
            return json_encode(['code'=>200,'msg'=>'请求成功','collection_list'=>$collection_list]);
        }else{
            return json_encode(['code'=>201,'msg'=>'暂无商品收藏']);
        }

    }

    //京东小白授权
    //如果当前用户未授权，需要先申请授权，跳转到授权页面
    public function jdAuthorization(){
          //从商户侧唤醒授权（根据环境正确使用http或https头）;http://[域名]/oauth2/bind?merchantCode=[商户号]&callBack=[转义后的商户回调地址];
          $user_id = input('post.user_id');
          // $user_id = 4;
          if(!is_numeric($user_id)){
             return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
          }
          $map = "user_id = {$user_id}";
          //jd_integral京东积分  quota 押金额度 frozen_integral 冻结押金 available_integral 可用押金 jd_integral_time 获取京东积分时间
          $user_info = db('user')->field('jd_openid,jd_integral,quota,frozen_integral,available_integral,jd_integral_time')->where($map)->find();
          // var_dump($user_info);
          //京东小白信用有效天数;
          $effective_day = db('config')->where("name = 'effective'")->value('value');
          $integral_effective_day = (int) $effective_day;
          // var_dump($user_info['jd_integral']);
//          if($user_info['jd_integral'] == "0.00"){
//             return json_encode(['code'=>201,'msg'=>'您还没有京东小白信用,请跳转至授权页面授权']);
//          }else{
             //如果当前时间 - 京东小白授权时间 > 后台设置小白信用有效天数,此时需要重新授权京东小白,获取新的小白信用
             // if(floor((time() - $user_info['jd_integral_time'])/86400) > $integral_effective_day ){
             //         $userData = [];
             //         $userData['jd_integral'] = 0.00;
             //         $userData['quota'] = 0.00;
             //         if($user_info['frozen_integral'] == "0.00"){
             //             $userData['frozen_integral'] = 0.00;
             //         }
             //         $userData['available_integral'] = ($user_info['quota'] - $user_info['frozen_integral'])>0?($user_info['quota'] - $user_info['frozen_integral']):0;
             //         $userData['jd_integral_time'] = '';
             //         db('user')->where($map)->update($userData);
             //         return json_encode(['code'=>401,'msg'=>'京东小白信用已过期,请重新授权']);
             // }
             return json_encode(['code'=>200,'msg'=>'您已有京东小白信用,无须重新授权','user_info'=>$user_info]);
//          }
    }

    //获取京东openID及京东小白信用等
    public function getJdInfo(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        //accessToken 与 jdopenId 二选一
        $accessToken = input('post.accessToken');
        $openId = input('post.jd_openid');
        //业务测试数据,json格式
        if($accessToken){
            $data = '{"accessToken":"'.$accessToken.'"}'; 
        }
        if($openId){
            $data = '{"openId":"'.$openId.'"}';
        }
        if(!$accessToken && !$openId){
            return json_encode(['code'=>401,'msg'=>'accessToken或jdopenId参数缺失']);
        }

        // var_dump($data);
        //DES加密
        $reqData = $this->des_encrypt($data,$this->des_key);
        $reqData = $reqData.",".base64_encode($this->des_key);
        //RSA加密
        $reqData     = $this->rsa_encrypt($reqData,$this->public_pfile);

        //RSA签名
        $reqData     = $this->rsa_sign($reqData,$this->private_file);
        //拼装参数
        $sign    = urlencode($reqData);
        $submitData = array(
            'merchantCode'  =>  $this->merchantCode,
            'data'      =>  $sign
        );
        // var_dump($submitData);
        //echo http_build_query($submitData);
        //提交数据
        $rows = $this->postData(array(
            'url'       =>  'https://'.Config::get('jdxiaobai.http_host').'/access/rights',
            'data'  =>  $submitData,
        ));
        // var_dump($rows);
        if($rows["responseCode"]=="0000"){
                $data = $rows["data"];
                $data = urldecode($data);
                $str = explode(",",$data);//通过,拆解字符串
                //RSA验签
                $verify = $this->verify($str[0],$str[1],$this->public_pfile);
                if($verify=="1")
                {
                    $data = $str[0];
                    //RSA解密
                    $data = $this->rsa_design($data,$this->private_file);
                    // if($data==""){ echo "RSA解密失败";return; }
                    if($data == ""){return json_encode(204);}//RSA解密失败
                    //DES解密
                    $str = explode(",",$data);//通过,拆解字符串
                    $reqData = $this->des_decrypt($str[0],base64_decode($str[1]));
                    $info = json_decode($reqData,true);
                    $jd_openids = db('user')->column('jd_openid');
                    if(in_array($info["openId"],$jd_openids)){
                        return json_encode(205);//该京东用户已授权,请选择新账号授权
                    }

                    // print_r($info);//打印返回数据
                    //$openid = $info["openid"];  //用户权益openid
                    $userData = [];
                    $userData['jd_openid'] = $info["openId"];
                    $userData['jd_integral'] = $info[101];
                    $userData['jd_integral_time'] = time();
                    $max_integral = db('config')->where("name = 'js_integral'")->value('value');
                    if((int) $info[101] > (int) $max_integral){
                        $quota = db('config')->where("name = 'mortgage'")->value('value');//后台设置的押金额度
                        $userData['quota'] = $quota;
                        $integral_info = db('user')->field('frozen_integral,available_integral')->where("user_id = {$user_id}")->find();
                        //如果冻结押金为0&&可用押金为0,或者冻结押金为0&&可用押金==押金额度
                        // if($integral_info['frozen_integral'] == 0 && ($integral_info['available_integral'] == 0 || $integral_info['available_integral'] == $quota)){
                        //     $userData['available_integral'] = $quota; 
                        // } 
                        // 可用额度的计算  可用额度 = （总额度 - 冻结额度）> 0 ?总额度-冻结额度:0;
                        $userData['available_integral'] = ($quota - $integral_info['available_integral']) > 0 ?($quota - $integral_info['available_integral']):0;
                    }
                    // $user_jd_info = [];
                    // $user_jd_info['jd_openid'] = $info["openId"];
                    // $user_jd_info['jd_integral'] = $info[101];
                    // if(isset($userData['available_integral'])){$user_jd_info['available_integral'] = $userData['available_integral'];}
                    $record = [];
                    $record['user_id'] = $user_id;
                    $record['jd_info'] = json_encode($info);
                    $record['create_time'] = time();
                    Db::startTrans();
                    try{
                        db('user')->where("user_id = {$user_id}")->update($userData);
                        db('user_jdinfo_record')->insert($record);
                        Db::commit();
                        return json_encode(200);//用户京东信息保存成功
                    }catch(\Exception $e){
                        Db::rollback();
                        return json_encode(201);//201用户京东信息保存失败
                    }
                }else{
                    // echo "RSA验签失败";return;
                    return json_encode(202);//RSA验签失败
                }
        }else{
                // echo $rows["responseMessage"];  //错误
                return json_encode(203);//获取京东用户信息失败
        }
    }

    //用户解绑京东授权
    public function unbindJdxiaobai(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){
            return json_encode(['code'=>401,'msg'=>'user_id类型错误']);
        }
        $openId = input('post.jd_openid');
        if($openId == '' || $openId == 'null' || $openId == 'undefined'){
            return json_encode(['code'=>401,'msg'=>'jd_openid参数缺失']);
        }
        if($openId){
            $data = '{"openId":"'.$openId.'"}';
        }
        
        //DES加密
        $reqData = $this->des_encrypt($data,$this->des_key);
        $reqData = $reqData.",".base64_encode($this->des_key);
        //RSA加密
        $reqData     = $this->rsa_encrypt($reqData,$this->public_pfile);
        //RSA签名
        $reqData     = $this->rsa_sign($reqData,$this->private_file);
        //拼装参数
        $sign    = urlencode($reqData);
        $submitData = array(
            'merchantCode'  =>  $this->merchantCode,
            'data'      =>  $sign
        );

        //提交数据
        $rows = $this->postData(array(
            'url'       =>  'https://'.Config::get('jdxiaobai.http_host').'/oauth2/unbind',
            'data'  =>  $submitData,
        ));
        if($rows["responseCode"]=="0000"){
              $jdInfo = [];
              $jdInfo['jd_openid'] = '';
              $jdInfo['jd_integral'] = 0.00;
              $jdInfo['quota'] = 0.00;
              // $jdInfo['frozen_integral'] = 0.00;
              // $jdInfo['available_integral'] = 0.00;
              $jdInfo['jd_integral_time'] = 0;
              $integral_info = db('user')->field('quota,frozen_integral,available_integral')->where("user_id = {$user_id}")->find();
              //如果冻结押金为0
              if($integral_info['frozen_integral'] == 0){
                  $jdInfo['frozen_integral'] = 0.00; 
              } 
              // if($integral_info['available_integral'] == 0){
              //     $jdInfo['available_integral'] = 0.00;
              // }
              // 可用额度的计算  可用额度 = （总额度 - 冻结额度）> 0 ?总额度-冻结额度:0;
              $jdInfo['available_integral'] = ($integral_info['quota'] - $integral_info['frozen_integral']) > 0 ?($integral_info['quota'] - $integral_info['frozen_integral']):0;
              db('user')->where("user_id = {$user_id}")->update($jdInfo);
              // return json_encode(['code'=>200,'msg'=>'用户解绑京东授权成功']);  
              return json_encode(200);
        }else{
                // echo $rows["responseMessage"];  //错误
              // return json(['code'=>201,'msg'=>'用户解绑京东授权失败','errmessage'=>$rows["responseMessage"]]);
              return json_encode(201);
        }
    }

    /**
     * DES加密 - 提交数据
     * @param $str
     * @param $key
     * @return string
     */
    public function des_encrypt($str, $key)  {
        $block = mcrypt_get_block_size('des', 'ecb');
        $pad = $block - (strlen($str) % $block);
        $str .= str_repeat(chr($pad), $pad);
        $str = mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
        return base64_encode($str);
    }

    /**
     * DES解密 - 返回数据
     * @param $str
     * @param $key
     * @return string
     */
    public function des_decrypt($str, $key) {
        $str = base64_decode($str);
        $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
        $block = mcrypt_get_block_size('des', 'ecb');
        $pad = ord($str[($len = strlen($str)) - 1]);
        return substr($str, 0, strlen($str) - $pad);
    }

    /**
     * RSA签名
     * @param $content
     * @param $rsaPrivateKeyPem
     * @return string
     */
    public function rsa_sign($data,$private_file) {
        if (empty($data))
        {
                return false;
        }
        if(file_exists($private_file))
        {
            $pricode = file_get_contents($private_file);
        }else{
            // exit('不能使用private文件不存在');
            return false;
        }
        $priKey = openssl_pkey_get_private($pricode);
        if(!$priKey){
            // exit('不能使用private.pem');
            return false;
        }
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res, OPENSSL_ALGO_MD5);
        openssl_free_key($res);
        $sign = $data.",".base64_encode($sign);
        return $sign;
    }

    /**
     * RSA解密
     * @param $content
     * @param $rsaPrivateKeyPem
     * @return string
     */
     public function rsa_design($data,$private_file) {

             if (empty($data))
             {
                     return false;
             }
             //$data = base64_decode($data);
             if(file_exists($private_file))
             {
                     $pricode = file_get_contents($private_file);
             }else{
                     // exit('不能使用private文件不存在');
                     return false;
             }
             $pkeyid = openssl_pkey_get_private($pricode);
             if(!$pkeyid){
                     // exit('不能使用private.pem');
                     return false;
             }
            $split = str_split(base64_decode($data), 128);// 1024bit  固定172
            $decode_data = "";
            foreach ($split AS $part) {
                 $isOkay = openssl_private_decrypt($part, $de_data, $pkeyid);// base64_decode($part) base64在这里使用，因为172字节是一组，是encode来的
                 $decode_data.= $de_data;
                 if(!$isOkay){
                        // echo "解密分解解析错误";
                        return false;
                 }
            }
            return $decode_data;
     }

    /**
      *  RSA加密
      * 利用约定数据和秘钥生成数字签名
      * @param $data 待加密数据
      * @return String 返回数据base64_encode
    */
    public function rsa_encrypt($data='',$public_pfile)
    {
        if (empty($data))
        {
                return false;
        }
        if(file_exists($public_pfile))
        {
            $pricode = file_get_contents($public_pfile);
        }else{
            // exit('不能使用public文件不存在');
            return false;
        }

        $priKey =  openssl_pkey_get_public($pricode);

        if (!$priKey)
        {
                // echo "Public key resource identifier False!";
                return false;
        }
        openssl_public_encrypt($data,$encrypted,$priKey);
        // 加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
        $encrypted = base64_encode($encrypted);
        return $encrypted;
    }

    /**
     * 利用公钥和数字签名以及约定数据验证合法性
     * @param $data 待验证数据
     * @param $signature 数字签名
     * @return -1:error验证错误 1:correct验证成功 0:incorrect验证失败
     */
    public function rsa_decrypt($data='',$public_file)
    {
            if (empty($data))
            {
                    return false;
            }
            // echo $data;exit;
            $data = base64_decode($data);
            if(file_exists($public_file)){
                    $public_key = file_get_contents($public_file);
            }
            if (empty($public_key))
            {
                    // echo "Public Key error!";
                    return false;
            }
            $pkeyid = openssl_pkey_get_public($public_key);
            if (empty($pkeyid))
            {
                    // echo "public key resource identifier False!";
                    return false;
            }
            $decrypted = "";
            openssl_public_decrypt($data,$decrypted,$pkeyid,OPENSSL_ALGO_MD5);//公钥解密
            //$decrypted = base64_encode($decrypted);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
            return $decrypted;
    }

    // RSA验签
    public function verify($data, $sign, $publicRsaPath)  {
        //读取公钥文件
        $pubKey = file_get_contents($publicRsaPath);
        //转换为openssl格式密钥
        $res = openssl_get_publickey($pubKey);
        //调用openssl内置方法验签，返回bool值
        $result = (bool) openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_MD5);
        //释放资源
        openssl_free_key($res);
        //返回资源是否成功
        return $result;
    }

    /**
     * 普通CRUL的方法:post,get
     * @param array $_param
     * url = 访问的地址
     * data = 提交的数据
     * type = 提交模式:GET,POST
     * header = 头协议
     * @return array|bool|json
     */
    public function postData($_param=array()){
            $url    = isset($_param['url']) ? $_param['url'] : '';
            $data = isset($_param['data']) ? $_param['data'] : array();
            $type = isset($_param['type']) ? $_param['type'] : 'POST';
            $header = isset($_param['header']) ? $_param['header'] : null;
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            if($header) {
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            }
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36');
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
            if($type=='POST'){
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//数据
            }
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $body = curl_exec($ch);
            curl_close($ch);
            return self::json($body);
    }

    /**
     * 对json进行编码或解码
     * @param null $data
     * @param int $DataType
     * @return bool | array | json
     */
    public function json($data=null,$DataType=1)
    {
            if($data){
                    if(is_array($data)){
                            header('Content-type:application/json');
                            return json_encode($data);
                    }else{
                            return json_decode($data,$DataType);
                    }
            }else{
                    is_exit(lang('is_json'));
            }
    }

    //我的优惠券
    public function myCouponList(){
        $user_id = input('post.user_id');
        // $user_id = 3;
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $state = input('post.state');//state 0未使用;1已使用;2已过期;
        // $state = 2;
        if($state){if(!is_numeric($state)){return json_encode(['code'=>401,'msg'=>'state类型错误']);}}else{$state = 0;}
        $page = input('post.page');
        if($page){if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page类型错误']);}}else{$page = 0;}
        $coupon_list = db('coupons_use')->field('use_id,coupons_id')
                                        ->where("user_id = {$user_id} AND state = {$state}")
                                        ->order("receive_time desc")->paginate(10)->toArray();
        // echo db('coupons_use')->getLastSql();
        // dump($coupon_list);die;
        foreach($coupon_list['data'] as $key=>$value){
            $coupon_info = db('coupons')->field('name,coupons_type,scope,start_time,settlement_time')
                                        ->where("coupons_id = {$value['coupons_id']}")
                                        ->find();
            $coupon_list['data'][$key]['name'] = $coupon_info['name'];
            $coupon_list['data'][$key]['coupons_type'] = $coupon_info['coupons_type'];//1满减;2折扣
            $coupon_list['data'][$key]['scope'] = $coupon_info['scope'];//0会员卡;1共享商品;2所有销售商品;其它值为部分销售商品
            $coupon_list['data'][$key]['start_time'] = date("Y.m.d",$coupon_info['start_time']);
            $coupon_list['data'][$key]['settlement_time'] = date("Y.m.d",$coupon_info['settlement_time']);
        }
        $unused_coupon_num = db('coupons_use')->where("user_id = {$user_id} AND state = 0")->count();
        $used_coupon_num = db('coupons_use')->where("user_id = {$user_id} AND state = 1")->count();
        $expired_coupon_num = db('coupons_use')->where("user_id = {$user_id} AND state = 2")->count();
            return json_encode([
                              'code'=>200,
                              'msg'=>'请求成功',
                              'coupon_list'=>$coupon_list,
                              'unused_coupon_num'=>$unused_coupon_num,
                              'used_coupon_num'=>$used_coupon_num,
                              'expired_coupon_num'=>$expired_coupon_num
                              ]);

    }



}